import { useEffect, useState } from 'react';
import './style.less';
import Scratch from 'react-scratch-perfect';
import { GiftOutlined } from '@ant-design/icons';
import { Modal } from 'antd';
import Fingerprint from 'fingerprintjs2';
import { sampleSize } from 'lodash';
import { ticketInfo } from './config.data';

const MyScratch = ({ item, onSuccess }) => {
  const { id, content, img } = item;
  return (
    <div className="wrapper">
      <Scratch
        color="#ccc"
        img={img}
        size={20}
        percentage={100}
        clear={false}
        mode="move"
        onChange={p => {
          if (p > 30) {
            onSuccess(id);
          }
        }}
        className="scratch"
      >
        <div className="content">{content}</div>
      </Scratch>
    </div>
  );
};

export default function() {
  const defaultArr1 = JSON.parse(localStorage.getItem('scratch') || '[]');
  const defaultArr2 = JSON.parse(localStorage.getItem('tickets') || '[]');
  const [ids, setIds] = useState(defaultArr1);
  const [tickets, setTickets] = useState(defaultArr2);
  const handleSuccess = curr => {
    const newIds = Array.from(new Set([...ids, curr]));
    setIds(newIds);
    localStorage.setItem('scratch', JSON.stringify(newIds));
  };

  const createFingerprint = () => {
    Fingerprint.get(components => {
      // 参数只有回调函数时，默认浏览器指纹依据所有配置信息进行生成
      const values = components.map(component => component.value); // 配置的值的数组
      const murmur = Fingerprint.x64hash128(values.join(''), 31); // 生成浏览器指纹
      const prevBrowserId = localStorage.getItem('browserId');
      if (prevBrowserId !== murmur) {
        const targets = sampleSize(ticketInfo, 5);
        setTickets(targets);
        localStorage.setItem('browserId', murmur); // 存储浏览器指纹，在项目中用于校验用户身份和埋点
        localStorage.setItem('tickets', JSON.stringify(targets)); // 存储浏览器指纹，在项目中用于校验用户身份和埋点
      }
    });
  };

  const handleGiftClick = () => {
    let content = tickets
      .filter(item => ids.includes(item.id))
      .map(item => item.content)
      .join(' ，');
    if (!content) {
      content = '请先刮奖';
    }
    Modal.info({
      content,
    });
  };

  useEffect(() => {
    if (window.requestIdleCallback) {
      requestIdleCallback(() => {
        createFingerprint();
      });
    } else {
      setTimeout(() => {
        createFingerprint();
      }, 500);
    }
  }, []);
  return (
    <div className="carousel">
      <header>
        <h2 onClick={handleGiftClick}>
          <GiftOutlined />
          我的礼物
        </h2>
      </header>
      <main>
        {tickets.map(item => (
          <MyScratch key={item.id} item={item} onSuccess={handleSuccess} />
        ))}
      </main>
    </div>
  );
}
